// 存储登录人相关信息
import * as auth from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router/index'
export default {
  namespaced: true,
  // 1.定义变量(响应式)
  state: {
    // 登陆成功的token=>鉴权使用
    token: auth.getToken() || null,
    // 用户个人信息
    userInfo: {}

  },
  // 2.修改变量(定义修改变量的方法)
  mutations: {
    // status
    setToken (state, token) {
      state.token = token
      auth.setToken(token)
      console.log('5555', token)
    },
    delToken (state) {
      state.token = null
      auth.removeToken()
    },
    // 储存登录人信息
    setUserInfo (state, user) {
      state.userInfo = user
    },
    delUserInfo (state) {
      state.userInfo = {}
    }
  },
  // 一般定义后台请求方法
  actions: {
    async getTokenAction ({ commit }, formData) {
      const token = await login(formData)
      console.log('token', token)
      commit('setToken', token.data)
    },
    async getUserInfoAction ({ commit }) {
      const userInfo = await getUserInfo()
      console.log(userInfo)
      // 头像
      const photoInfo = await getUserDetailById(userInfo.data.userId)
      console.log(userInfo, photoInfo)
      commit('setUserInfo', { ...userInfo.data, ...photoInfo.data })
      // 将个人权限数据返回
      return userInfo.data.roles
    },
    logoutAction ({ commit }) {
      commit('delToken')
      commit('delUserInfo')
      // 清空路由缓存
      resetRouter()
      // 清空vuex缓存，只保留静态路由
      commit('router/setMenuList', [], { root: true })
    }
  }
}
